package com.dengjunbo.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dengjunbo.eduservice.entity.EduSubject;
import com.dengjunbo.eduservice.entity.excel.SubjectData;
import com.dengjunbo.eduservice.entity.subject.OneSubject;
import com.dengjunbo.eduservice.entity.subject.TwoSubject;
import com.dengjunbo.eduservice.listener.SubjectExcelListener;
import com.dengjunbo.eduservice.mapper.EduSubjectMapper;
import com.dengjunbo.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author dengjunbo
 * @since 2020-04-21
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
//   添加课程分类
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
//  课程列表分类实现
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        QueryWrapper<EduSubject> onewrapper = new QueryWrapper<>();
        onewrapper.eq("parent_id","0");
        List<EduSubject> oneSubjectsList = baseMapper.selectList(onewrapper);

        QueryWrapper<EduSubject> twowrapper = new QueryWrapper<>();
        onewrapper.ne("parent_id","0");
        List<EduSubject> twoSubjectsList = baseMapper.selectList(twowrapper);

        List<OneSubject> finalSubjectList = new ArrayList<>();

        for (int i = 0; i < oneSubjectsList.size(); i++) {
            EduSubject eduSubject = oneSubjectsList.get(i);
            OneSubject oneSubject = new OneSubject();

//            oneSubject.setId(eduSubject.getId());
//            oneSubject.setTitle(eduSubject.getTitle());
            BeanUtils.copyProperties(eduSubject,oneSubject);


            finalSubjectList.add(oneSubject);

            List<TwoSubject> children = new ArrayList<>();
            for (int m = 0; m < twoSubjectsList.size(); m++) {
                EduSubject eduSubject2 = twoSubjectsList.get(m);

                if (eduSubject2.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject =new TwoSubject();
                    BeanUtils.copyProperties(eduSubject2,twoSubject);
                    children.add(twoSubject);
                }
            }
            oneSubject.setChildren(children);
        }
        return finalSubjectList;
    }
}
